$(() => {
    //页面一进来加载网站配置数据
    $.ajax({
        type: 'get',
        url: '/settings',
        success(res) {
            $('#preview').attr('src', res.logo)
            $('#site_name').val(res.title)
            $('#site_description').val(res.description)
            $('#site_keywords').val(res.keywords)
            $('#comment_status').prop('checked', res.comment)
            $('#comment_reviewed').prop('checked', res.review)
        },
        error(res) {
            alert(JSON.parse(res.responseText).message)
        }
    })

    //图片上传
    $('#logo').change(function () {
        const formData = new FormData()
        formData.append('avatar', this.files[0])
        $.ajax({
            type: 'post',
            url: '/upload',
            data: formData,
            processData: false,
            contentType: false,
            success(res) {
                $('#preview').attr('src', res[0].avatar)
                $('#hiddenForm').val(res[0].avatar)
            }
        })
    })


    //表单提交
    $('#settingForm').submit(function () {
        const formData = $(this).serializeArray()
        const dataObj = {}
        formData.forEach((v) => {
            dataObj[v.name] = v.value
        })
        dataObj.comment = dataObj.comment === 'on'
        dataObj.review = dataObj.review === 'on'

        $.ajax({
            type: 'post',
            url: '/settings',
            data: dataObj,
            success(res) {
                alert('网站配置成功!')
            },
            error(res) {
                alert(JSON.parse(res.responseText).message)
            }
        })
        return false
    })
})